#include <msp430.h> 
#include <stdint.h>


/**
 * main.c
 */
typedef struct{
    const volatile uint8_t* PxIN;
    volatile uint8_t* PxOUT;
    volatile uint8_t* PxDIR;
    volatile uint8_t* PxREN;
    volatile uint8_t* PxSEL;
} GPIO_TypeDef;

const GPIO_TypeDef GPIO4 = {&P4IN,&P4OUT,&P4DIR,&P4REN,&P4SEL};
const GPIO_TypeDef GPIO5 = {&P5IN,&P5OUT,&P5DIR,&P5REN,&P5SEL};
const GPIO_TypeDef GPIO8 = {&P8IN,&P8OUT,&P8DIR,&P8REN,&P8SEL};

const GPIO_TypeDef * LED_GPIO[5] = {&GPIO4,&GPIO4,&GPIO4,&GPIO5,&GPIO8};
const uint8_t LED_PORT[5] = {BIT5,BIT6,BIT7,BIT7,BIT0};


int main(void)
{
	WDTCTL = WDTPW | WDTHOLD;	// stop watchdog timer
	while(BAKCTL & LOCKIO)
	    BAKCTL &= ~(LOCKIO);
	UCSCTL6 &= ~XT1OFF;
	while (UCSCTL7 & XT1LFOFFG)
	    UCSCTL7 &= ~(XT1LFOFFG);
	UCSCTL4 = SELA__XT1CLK + SELS__REFOCLK + SELM__REFOCLK;

	int i;
	for(i=0;i<5;++i)
	    *LED_GPIO[i]->PxDIR |= LED_PORT[i];
	P4REN |= 0x1F;
	P4OUT |= 0x1F;

	uint8_t last_btn = 0x1F, cur_btn, temp;
	while(1){
	    cur_btn = P4IN & 0x1F;
	    temp = (cur_btn ^ last_btn) & last_btn;
	    last_btn = cur_btn;
	    int i;
	    for(i = 0;i<5;++i)
	        if(temp & (1 << i))
	            *LED_GPIO[i]->PxOUT ^= LED_PORT[i];
	    __delay_cycles(3276);
	}
	
	return 0;
}
